# -*- coding: UTF-8 -*-
import configparser
import json
# from scp import SCPClient
import threading
from typing import List

import pymysql
import time

from bean.hot_new import HotNew
from news_platform.baidu import BaiDu
from news_platform.fenghuang import FengHuang
from news_platform.weibo import WeiBo
from news_platform.zhihu import ZhiHu
from news_platform.bendibao import BenDiBao

file_name = "html/hot_news.html"


def load_data():
    # create_file()
    # create_head()
    # news = zhihu.get_data()
    # create_news("知乎热榜", news)
    # news = baidu.get_data()
    # create_news("百度热搜", news)
    # news = weibo.get_data()
    # create_news("微博热搜", news)
    # news = bendibao.get_data()
    # create_news("本地宝", news)
    # create_tail()
    load_to_db()


def load_to_db():
    threading.Thread(target=BaiDu().execute, name="baidu").start()
    threading.Thread(target=ZhiHu().execute, name="zhihu").start()
    threading.Thread(target=WeiBo().execute, name="weibo").start()
    threading.Thread(target=FengHuang().execute, name="feng huang").start()
    threading.Thread(target=BenDiBao().execute, name="ben di bao").start()


def load_from_db():
    news_list = select()
    data = {}
    for hot_news in news_list:
        if len(hot_news) > 0:
            data[hot_news[0].type_id] = hot_news
    print(json.dumps(data, cls=MyEncoder, indent=4))
    json_file = open('html/hot_news.json', 'w')
    json_file.write(json.dumps(data, cls=MyEncoder, indent=4))
    json_file.close()
    # print(json.)
    create_file()
    create_head()
    for hot_news in news_list:
        if len(hot_news) > 0:
            create_news(hot_news[0].type_id, hot_news[0].new_type, hot_news[0].type_color, hot_news)
    create_tail()


def insert(news):
    conn = get_connection()
    sql = '''insert into hot_news(serial_no, type, title, link, ext_info, excerpt, app_path) 
                values (%s, %s, %s, %s, %s, %s, %s)'''
    cursor = conn.cursor()
    conn.begin()
    cursor.execute("delete from hot_news")
    cursor.executemany(sql, news)
    conn.commit()
    cursor.close()


def select() -> List[List[HotNew]]:
    conn = get_connection()
    sql = '''select ht.type, hn.serial_no, hn.title, hn.link, ht.type_name, hn.ext_info, hn.excerpt, 
            ht.color, ht.app_id, hn.app_path
            from hot_news hn left join hot_news_type ht on hn.type=ht.type order by hn.type, serial_no'''
    cursor = conn.cursor()
    conn.begin()
    cursor.execute(sql)
    db_data_list = cursor.fetchall()
    news_list: List[List[HotNew]] = []
    hot_news: List[HotNew] = []
    pre_type_name = ""
    for db_data in db_data_list:
        type_name = db_data[4]
        if type_name != pre_type_name:
            pre_type_name = type_name
            if len(hot_news) > 0:
                news_list.append(hot_news)
            hot_news = list()
        else:
            new = HotNew(db_data[1], db_data[2], db_data[3], db_data[4], db_data[5], db_data[6])
            new.type_id = db_data[0]
            new.type_color = db_data[7]
            new.app_id = db_data[8]
            new.app_path = db_data[9]
            hot_news.append(new)
    if len(hot_news) > 0:
        news_list.append(hot_news)
    conn.commit()
    cursor.close()
    return news_list


def get_connection():
    cf = configparser.ConfigParser()
    cf.read("conf/db.properties")
    conn = pymysql.connect(
        host=cf.get("mysql", "host"),
        user=cf.get("mysql", "user"),
        passwd=cf.get("mysql", "passwd"),
        db=cf.get("mysql", "db"),
        port=int(cf.get("mysql", "port")),
        charset=cf.get("mysql", "charset"))
    return conn


def create_file():
    file = open(file_name, 'w')
    file.close()


def create_head():
    file = open(file_name, 'a')
    file.write('''<!DOCTYPE html>
            <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <title>热搜榜单(2分钟更新一次)</title>
                    <script>
                        var colorDict = {
                            1: "#ff4d4d",
                            2: "#056de8",
                            3: "#ff8140",
                            4: "#ff6600"
                        }
                        function changeType(type) {
                            
                            var id = 'hot_news_' + type;
                            var hot_new_divs = document.getElementsByClassName('hot_news')
                            for (var i = 0; i < hot_new_divs.length; i ++) {
                                hot_new_divs[i].style.display = 'none';
                            }
                            var currentNew = document.getElementById(id)
                            if(currentNew) {
                                currentNew.style.display = 'block';
                            }
                            var hot_new_type_divs = document.getElementsByClassName('hot_news_type')
                            for (var i = 0; i < hot_new_type_divs.length; i ++) {
                                hot_new_type_divs[i].style.borderBottom = '';
                            }
                            var currentType = document.getElementById('hot_news_type_' + type);
                            if(currentType) {
                                currentType.style.borderBottom = '2px solid ' + colorDict[type];
                            }
                            
                        }
                    </script>
                </head>
                <body style='margin-top:0px;'>
                    <div style="height:60px;padding-top:20px;position:fixed;width:100%;background-color:white;">
                        <div id="hot_news_type_1" class="hot_news_type" 
                            style="float:left;width:25%;border-bottom: 2px solid #ff4d4d;
                            text-align:center;height:100%;font-size:40px;" onclick="changeType(1)">
                            百度热搜
                        </div>
                        <div id="hot_news_type_2" class="hot_news_type" 
                            style="float:left;width:25%;height:100%text-align:center;font-size:40px;text-align:center;" 
                            onclick="changeType(2)">
                            知乎热榜
                        </div>
                        <div id="hot_news_type_3" class="hot_news_type" 
                            style="float:left;width:25%;height:100%text-align:center;font-size:40px;text-align:center;" 
                            onclick="changeType(3)">
                            微博热搜
                        </div>
                        <div id="hot_news_type_4" class="hot_news_type" 
                            style="float:left;width:25%;height:100%text-align:center;font-size:40px;text-align:center;" 
                            onclick="changeType(4)">
                            本地资讯
                        </div>
                    </div>
                    ''')
    file.close()


def create_news(type_id, name, type_color, news: List[HotNew]):
    file = open(file_name, "a")
    display_style = ""
    if type_id != 1:
        display_style = "display:none;"
    file.write('''<div id="hot_news_''' + str(type_id) + '''" 
                    class="hot_news" style="margin-left:20px;padding-top:80px;font-size:32px;''' + display_style + '''">
                        <font style="font-size:62px;font-weight:bold;display:none;color:'''
               + type_color + ''';">''' + name + '''</font>
                            <ol>''')
    for new in news:
        li_ele = '''
        <li style="padding-bottom:60px;color:''' + type_color + ''';">
            <a style="text-decoration:none;padding-top:10px;color:#121212;font-weight:bold;" 
                href="''' + new.link + '''">
                ''' + new.title + '''
            </a>
            <font style="font-size:24px;color:''' + type_color + ''';font-weight:bold;">
            ''' + str(new.ext_info) + '''
            </font>
        </li>
        '''
        file.write(li_ele)
    file.write('''                            </ol>
    </div>''')
    file.close()


def create_tail():
    file = open(file_name, 'a')
    file.write('''
                        
                    </body>
                </html>''')
    file.close()


def upload():
    pass
    # ssh_client = paramiko.SSHClient()
    # ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
    # ssh_client.connect('123.57.3.130', 22, username='root', password='Wrf@0909')
    # scp_client = SCPClient(ssh_client.get_transport(), socket_timeout=15)
    # scp_client.put('/Users/wangruifeng/Desktop/work/py_project/hot_news/html/hot_news.html',
    #                '/home/z5u/hot_news/index.html')


class MyEncoder(json.JSONEncoder):
    pass
    # def default(self, obj):
    #     if isinstance(obj, numpy.ndarray):
    #         return obj.tolist()
    #     elif isinstance(obj, bytes):
    #         return str(obj, encoding='utf-8')
    #     elif isinstance(obj, HotNew):
    #         res = {}
    #         for f in dir(obj):
    #             value = getattr(obj, f)
    #             if not f.startswith("__") and not callable(value):
    #                 res[f] = value
    #         return res
    #     return json.JSONEncoder.default(self, obj)


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    while True:
        load_data()
        time.sleep(300)
    # while True:
    #     print("开始更新")
    #     load_data()
    #     print("更新完成")
    #     try:
    #         print("开始上传")
    #         # upload()
    #         print("上传完成")
    #     except Exception as e:
    #         print(e)
    #     time.sleep(120)

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
